package rxgo

import (
	"context"
	"reflect"
	"sync"
	"time"
	"fmt"
)

type filterFunc func(context.Context, interface{}) (interface{}, error)

type filtOperator struct {
	opFunc func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool)
}

func (ftop filtOperator) op(ctx context.Context, o *Observable) {
	// must hold definition of flow resources here, such as chan etc., that is allocated when connected
	// this resources may be changed when operation routine is running.
	in := o.pred.outflow
	out := o.outflow
	//fmt.Println(o.name, "source out chan ", out)
	var wg sync.WaitGroup

	go func() {
		end := false
		for x := range in {
			if end {
				continue
			}
			// can not pass a interface as parameter (pointer) to gorountion for it may change its value outside!
			xv := reflect.ValueOf(x)
			// send an error to stream if the flip not accept error
			if e, ok := x.(error); ok && !o.flip_accept_error {
				o.sendToFlow(ctx, e, out)
				continue
			}
			// scheduler
			switch threading := o.threading; threading {
			case ThreadingDefault:
				if ftop.opFunc(ctx, o, xv, out) {
					end = true
				}
			case ThreadingIO:
				fallthrough
			case ThreadingComputing:
				wg.Add(1)
				go func() {
					defer wg.Done()
					if ftop.opFunc(ctx, o, xv, out) {
						end = true
					}
				}()
			default:
			}
		}
		if o.flip != nil {
			buffer := (reflect.ValueOf(o.flip))
			if buffer.Kind() != reflect.Slice {
				panic("flip is not buffer")
			}
			for i := 0; i < buffer.Len(); i++ {
				o.sendToFlow(ctx, buffer.Index(i).Interface(), out)
			}
		}
		wg.Wait() //waiting all go-routines completed
		o.closeFlow(out)
	}()
}

func (parent *Observable) Debounce(timespan time.Duration) (o *Observable) {
	o = parent.newFilterObservable("debounce")
	o.timespan = timespan
	o.count = 0
	o.operator = debounceOperator
	return o
}

var debounceOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	o.count++
	times := o.timespan
	go func() {
		tempCount := o.count
		time.Sleep(times)
		select {
		case <-ctx.Done():
			return 
		default:
			if tempCount == o.count {
				o.sendToFlow(ctx, item.Interface(), out)
			}
		}
	}()
	return false
}}

func (parent *Observable) Distinct() (o *Observable) {
	o = parent.newFilterObservable("distinct")
	o.operator = distinctOperator
	o.keyset = map[string]bool{}
	return o
}

var distinctOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	itemStr := fmt.Sprintf("%v", item)
	if _, ok := o.keyset[itemStr]; !ok {
		o.keyset[itemStr] = true
		o.sendToFlow(ctx, item.Interface(), out)
	}
	return false
}}

func (parent *Observable) ElementAt(index uint) (o *Observable) {
	o = parent.newFilterObservable("ElementAt")
	o.operator = elementatOperator
	o.num = int(index)
	o.count = 0
	return o
}

var elementatOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	if o.count == o.num {
		o.sendToFlow(ctx, item.Interface(), out)
		return true
	}
	o.count++
	return false
}}

func (parent *Observable) First() (o *Observable) {
	o = parent.newFilterObservable("First")
	o.operator = firstOperator

	return o
}

var firstOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	o.sendToFlow(ctx, item.Interface(), out)
	return true
}}

func (parent *Observable) Last() (o *Observable) {
	o = parent.newFilterObservable("Last")
	o.operator = lastOperator

	return o
}

var lastOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	o.flip = append([]interface{}{}, item.Interface())
	return false
}}

func (parent *Observable) IgnoreElements() (o *Observable) {
	o = parent.newFilterObservable("IgnoreElements")
	o.operator = ignoreelementsOperator

	return o
}

var ignoreelementsOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	return false
}}

func (parent *Observable) Skip(n uint) (o *Observable) {
	o = parent.newFilterObservable("Skip")
	o.operator = skipOperator
	o.num = int(n)
	o.count = 0
	return o
}

var skipOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	if o.count == o.num {
		o.sendToFlow(ctx, item.Interface(), out)
	} else {
		o.count++
	}
	return false
}}

func (parent *Observable) SkipLast(n uint) (o *Observable) {
	o = parent.newFilterObservable("SkipLast")
	o.operator = skiplastOperator
	o.num = int(n)
	o.count = 0
	return o
}

var skiplastOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	if o.count == o.num {
		o.sendToFlow(ctx, o.last[0], out)
		o.last = o.last[1:]
	} else {
		o.count++
	}
	o.last = append(o.last, item.Interface())
	return false
}}

func (parent *Observable) Take(n uint) (o *Observable) {
	o = parent.newFilterObservable("Take")
	o.num = int(n)
	o.count = 0
	o.operator = takeOperator
	return o
}

var takeOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	o.count++
	if o.count > o.num {
		return true
	}
	o.sendToFlow(ctx, item.Interface(), out)
	return false
}}

func (parent *Observable) TakeLast(n uint) (o *Observable) {
	o = parent.newFilterObservable("TakeLast")
	o.operator = takelastOperator
	o.num = int(n)
	o.count = 0
	return o
}

var takelastOperator = filtOperator{opFunc: func(ctx context.Context, o *Observable, item reflect.Value, out chan interface{}) (end bool) {
	o.count++
	if o.count <= o.num {
		o.last = append(o.last, item.Interface())
	} else {
		o.last = o.last[1:]
		o.last = append(o.last, item.Interface())
	}
	o.flip = o.last
	return false
}}

func (parent *Observable) newFilterObservable(name string) (o *Observable) {
	//new Observable
	o = newObservable()
	o.Name = name

	//chain Observables
	parent.next = o
	o.pred = parent
	o.root = parent.root

	//set options
	o.flip_accept_error = true
	return o
}